<script>
  import { Route, Router, Link, navigate } from "svelte-routing";
  import { routes } from "./routes/routes";
  import PrivateRoute from "./components/PrivateRoute.svelte";
  import { user, theme, toggleTheme } from "./store/index";
  import { writable } from "svelte/store";
  import { logout } from "./api";
  let num = 111;
  let num_store = writable(num);
  let arr = [1, 2, 3];
  let flag = true;
</script>

<Router>
  <!-- {num}
  {$num_store}
  {#each arr as item}
    {item}
  {/each}
  {#if flag}
    <p>flag is true</p>
  {:else}
    <p>flag is false</p>
  {/if} -->
  {#if $user}
    <nav class="bg-white dark:bg-gray-800 shadow-md fixed top-0 w-full z-10">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex">
            {#each routes as route}
              {#if $user && route.roles && route.show && route.roles.includes($user.role)}
                <Link
                  key={route.path}
                  to={route.path}
                  class="ml-4 flex items-center px-4 py-2 border-b-2 border-transparent text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-300 dark:hover:text-white dark:hover:border-gray-700"
                >
                  {route.name}
                </Link>
              {/if}
            {/each}
          </div>
          <div class="flex items-center">
            <span class="mr-4">{`欢迎, ${$user.username}`}</span>
            <button
              on:click={logout}
              class="mr-4 px-3 py-1 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-white hover:bg-gray-700 dark:hover:bg-gray-600 rounded-md"
            >
              退出
            </button>
            <button
              on:click={toggleTheme}
              class="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
              aria-label={$theme === "light"
                ? "切换到暗黑模式"
                : "切换到明亮模式"}
            >
              {#if $theme === "light"}
                <i class="fas fa-moon"></i>
              {:else}
                <i class="fas fa-sun"></i>
              {/if}
            </button>
          </div>
        </div>
      </div>
    </nav>
  {/if}
  <main class="max-w-7xl mx-auto h-dvh mt-16 px-4 sm:px-6 lg:px-8 py-8 h-class">
    {#each routes as route}
      {#if route.public}
        <Route path={route.path} component={route.component} />
      {:else}
        <Route path={route.path} let:params>
          <PrivateRoute
            component={route.component}
            roles={route.roles}
            path={route.path}
            {...params}
          />
        </Route>
      {/if}
    {/each}
  </main>
</Router>

<style>
  .h-class {
    height: calc(100dvh - 64px);
  }
</style>
